#!/bin/python3

import numpy as np
import argparse
import matplotlib.pyplot as plt
from pylab import mpl 
from matplotlib.font_manager import FontProperties

parser = argparse.ArgumentParser(description='Visualization of Corp Analysis Report')
parser.add_argument('-t','--target', type=str, default = '000001',help='the object code of corp target.')
parser.add_argument('-s','--show', type=int, default = 1,help='show the graph or save it to png file(default:1(show)).')
args = parser.parse_args()
print('target:' ,args.target)
print('show:',args.show)

invest_target = '../data/'+args.target
skip_rows = 0
with open(invest_target + '.md','r') as datafile:
    data_version = datafile.readline()
    if 'data_version' in data_version.split(':')[0]:
        data_rev = (int)(data_version.split(':')[1],16)
        skip_rows = data_rev&0xff
raw_data = np.loadtxt(invest_target+'.md',comments='#',delimiter='|',skiprows=skip_rows)

with open(invest_target + '_rate.md','r') as datafile:
    data_version = datafile.readline()
    if 'data_version' in data_version.split(':')[0]:
        data_rev = (int)(data_version.split(':')[1],16)
        skip_rows = data_rev&0xff
rate_data = np.loadtxt(invest_target + '_rate.md',comments='#',delimiter='|',skiprows=skip_rows)

# 设置中文字体  
#mpl.rcParams['font.sans-serif'] = ['SimHei']  
zhfont = mpl.font_manager.FontProperties(fname='/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc')

min_raw_val = raw_data[:,1:8].min();
if min_raw_val > 0:
    min_raw_val = min_raw_val*0.8
else:
    min_raw_val = min_raw_val*2.0

max_raw_val = raw_data[:,1:8].max();
if max_raw_val > 0:
    max_raw_val = max_raw_val*1.2
else:
    max_raw_val = max_raw_val*0.8

min_rate_val = rate_data[:,1:8].min();
if min_rate_val > 0:
    min_rate_val = min_rate_val*0.8
else:
    min_rate_val = min_rate_val*1.2

max_rate_val = rate_data[:,1:8].max();
if max_rate_val > 0:
    max_rate_val = max_rate_val*2.0
else:
    max_rate_val = max_rate_val*0.8
# RawData: Date|income|net_margin|total_assets|net_assets|cashin|net_cashin
#
# RateData: rate_equity_multiplier|rate_net_margin|rate_asset_turnover|rate_asset_margin|
#   rate_equity_margin|rate_cash_income|rate_cash_margin|
plt.figure(1,figsize=(12.8,7.2))
plt.suptitle(args.target + '财务分析',fontproperties=zhfont,fontsize=16)
plt.subplot(2,2,1)
#plt.xticks(np.arange(min(raw_data[:,0]),max(raw_data[:,0])+1,1))
plt.xticks([])
#plt.ylim(min_raw_val,max_raw_val)
plt.ylabel('亿元人民币',fontproperties=zhfont)
for i in range(raw_data.shape[1]-1):
    plt.plot(raw_data[:,0],raw_data[:,i+1],'o-')

#plt.legend((u'营收','net_margin','total_asset','net_asset','cashin','net_cashin'),
plt.legend((u'营收',u'净利润','总资产','净资产','现金流入','净现金流入'),
            loc='upper left', prop=zhfont, bbox_to_anchor=(0, -0.1,1.0,.102),ncol=4,mode="expand",borderaxespad=0.)
           #loc='upper left', prop=zhfont,ncol=3)

plt.subplot(2,2,2)
plt.xticks(np.arange(min(raw_data[:,0]),max(raw_data[:,0])+1,1))
plt.plot(raw_data[:,0],raw_data[:,2],'s-',label='净利润')
plt.plot(raw_data[:,0],raw_data[:,6],'p-',label='净现金流入')
plt.legend((u'净利润','净现金流入'), loc='upper left',prop=zhfont,ncol=2)

plt.subplot(2,2,3)
#plt.xticks(np.arange(min(rate_data[:,0]),max(rate_data[:,0])+1,1))
plt.xticks([])
#plt.ylim(min_rate_val,max_rate_val)
for i in range(rate_data.shape[1]-1):
    plt.plot(rate_data[:,0],rate_data[:,i+1],'^-')

#===============================================================================
# plt.legend(('rate_equity_multiplier','rate_net_margin',
#             'rate_asset_turnover','rate_asset_margin',
#             'rate_equity_margin','rate_cash_income','rate_cash_margin'),loc='upper left',
#             prop=zhfont,
#            bbox_to_anchor=(1, 1),ncol=1)
#===============================================================================
plt.legend(('权益乘数','净利润率', '总资产周转率','ROA',
            'ROE','营收含金量','净利含金量'),
            loc='upper left', prop=zhfont, bbox_to_anchor=(0, -0.1,1.0,.102),ncol=4,mode="expand",borderaxespad=0.)
            #loc='upper left', prop=zhfont,ncol=3)
#plt.xlabel('时间',fontproperties=zhfont)

plt.subplot(2,2,4)
plt.plot(rate_data[:,0],rate_data[:,2],'s-',label='净利润率')
plt.plot(rate_data[:,0],rate_data[:,4],'d-',label='ROA')
plt.plot(rate_data[:,0],rate_data[:,5],'D-',label='ROE')
plt.xticks(np.arange(min(rate_data[:,0]),max(rate_data[:,0])+1,1))
plt.legend(('净利润率', 'ROA', 'ROE'),loc='upper left', prop=zhfont, ncol=3)

#plt.subplots_adjust(left=0.1,bottom=0.1,right=0.8, top=0.95,hspace=0.1,wspace=0.7)
plt.subplots_adjust(left=0.10,bottom=0.1,right=0.90, top=0.90,hspace=0.18,wspace=0.12)

if args.show:
    plt.show()
else:
    plt.savefig(invest_target + '_graph.png')
    plt.close()

